package fr.starn.domoticz_widgets;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import fr.starn.domoticz_widgets.JSonObject.DeviceProps;
import fr.starn.domoticz_widgets.JSonObject.DevicesProps;
import android.os.Bundle;
import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class ConfigureWidgetStep2 extends Activity implements OnClickListener {
	int widgetID;
	
	boolean ssl;
	String host;
	int port;
	String login;
	String pwd;
	
	String device;
	Map<String,String> deviceLabelToName;
	
	int thisWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.configure_widget2);
		
		host=this.getIntent().getStringExtra("host");
		port=this.getIntent().getIntExtra("port",-1);
		ssl=this.getIntent().getBooleanExtra("ssl",false);
		login=this.getIntent().getStringExtra("login");
		pwd=this.getIntent().getStringExtra("pwd");
		widgetID=this.getIntent().getIntExtra("widgetID",0);
		
		
		DevicesProps devicesJSON =DevicesProps.deserialize( this.getIntent().getStringExtra("devicesJSON"));
		
		RadioGroup radioGroup = (RadioGroup)findViewById(R.id.devices);
		List<DeviceProps> devices = devicesJSON.getResult();
		deviceLabelToName = new HashMap<String,String>();
		for (DeviceProps device:devices){
			String label = device.getName()+" - "+device.getType();
			deviceLabelToName.put(label, device.getName());
			RadioButton btn1 = new RadioButton(this);
			btn1.setText(label);
			radioGroup.addView(btn1);
		}
		
		Button okButton = (Button)findViewById(R.id.button1);
		okButton.setOnClickListener(this);
	}

//////////////////////// not used for now
	




	@Override
	public void onClick(View view) {
		RadioGroup radioGroup = (RadioGroup)findViewById(R.id.devices);
	    int id= radioGroup.getCheckedRadioButtonId();
	    this.device="";
	    if (id!=-1){
		    View radioButton = radioGroup.findViewById(id);
		    int radioId = radioGroup.indexOfChild(radioButton);
		    RadioButton btn = (RadioButton) radioGroup.getChildAt(radioId);
		    device = deviceLabelToName.get((String) btn.getText().toString());
	    } else {
			Toast.makeText(this.getApplicationContext(),"You must select a device to display", Toast.LENGTH_LONG).show();
			return;
	    }
		

	    Intent returnIntent = new Intent();
	    returnIntent.putExtra("result",device);
	    setResult(RESULT_OK,returnIntent);     
	    finish();
	}

	
	

}
